﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Xml;
using umbraco.IO;

namespace TheOutfield.UmbExt.AutoExport2DotNet
{
    public class Config
    {
        #region Singleton

        private static Config _instance;

        public static Config Instance
        {
            get
            {
                if (_instance == null)
                    _instance = new Config();

                return _instance;
            }
        }

        private Config()
        {
            Outputs = new Dictionary<string, Output>();

            LoadXmlConfig();
        }

        #endregion

        public string Mode { get; set; }
        public string DataContextName { get; set; }
        public string Namespace { get; set; }
        public Dictionary<string, Output> Outputs { get; set; }

        private void LoadXmlConfig()
        {
            XmlDocument xmlConfig = new XmlDocument();
            xmlConfig.Load(IOHelper.MapPath(Path.Combine(SystemDirectories.Config, "autoExport2DotNet.config")));
            var xmlConfigEntry = xmlConfig.SelectSingleNode("/autoExport2DotNet");
            if (xmlConfigEntry.NodeType == XmlNodeType.Element)
            {
                Mode = xmlConfigEntry.Attributes["mode"].Value;
                DataContextName = xmlConfigEntry.Attributes["datacontextname"].Value;
                Namespace = xmlConfigEntry.Attributes["namespace"].Value;
            }

            foreach (XmlNode xmlOutputEntry in xmlConfigEntry.SelectNodes("output"))
            {
                if (xmlOutputEntry.NodeType == XmlNodeType.Element)
                {
                    var machineName = xmlOutputEntry.Attributes["machinename"].Value.ToLower();
                    if (!Outputs.ContainsKey(machineName))
                    {
                        Outputs.Add(machineName,
                            new Output
                            {
                                OutputDirectory = xmlOutputEntry.Attributes["outputdir"].Value
                                    .Replace("~/", HttpContext.Current.Server.MapPath("~/"))
                                    .Replace("/", "\\"),
                                OutputFormat = (OutputFormat) Enum.Parse(typeof(OutputFormat), xmlOutputEntry.Attributes["format"].Value.ToUpper())
                            });
                    }
                }
            }
        }

        public class Output
        {
            public string OutputDirectory { get; set; }
            public OutputFormat OutputFormat { get; set; }
        }

        public enum OutputFormat
        {
            CS,
            DLL
        }
    }
}